<?php

namespace App\Http\Services;

/*
 *  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
use App\Http\Services\REST;

class sendTemplateSMS
{
    //主帐号
    private $accountSid = 'aaf98f8946b91a580146cbfc4f3703c1';
    //主帐号Token
    private $accountToken = 'e0029429eaac42eba7b29ecbe3465752';
    //应用Id
    private $appId = '8a216da85e6fff2b015e7e1b18230a30';
    //请求地址，格式如下，不需要写https://
    private $serverIP = 'app.cloopen.com';
    //请求端口
    private $serverPort = '8883';
    //REST版本号
    private $softVersion = '2013-12-26';
    private $REST;

    public function __construct()
    {
        $this->REST = new REST($this->serverIP, $this->serverPort, $this->softVersion);
        $this->REST->setAccount($this->accountSid, $this->accountToken);
        $this->REST->setAppId($this->appId);
    }

    /**
     * 发送模板短信
     * @param to 手机号码集合,用英文逗号分开
     * @param datas 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
     * @param $tempId 模板Id
     * $SMS->sendTemplateSMS('18507106389',array('123456','1分钟'),'204912');发123456的验证码 有效1分钟
     */
    public function sendTemplateSMS($to, $datas, $tempId = '204912')
    {
        // 发送模板短信
        $result = $this->REST->sendTemplateSMS($to, $datas, $tempId);
        $ret = [];
        if ($result == NULL) {
            $ret['error'] = '1';
            $ret['message'] = 'result error!';
        }
        if ($result->statusCode != 0) {
            //TODO 添加错误处理逻辑
            $ret['error'] = '1';
            $ret['message'] = 'error code: ' . $result->statusCode . ' error msg: ' . $result->statusMsg;
        } else {
            // 获取返回信息 信息为SimpleXMLElement Object，强制转换为数组
            $smsmessage = (array)($result->TemplateSMS);
            $dateCreated = $smsmessage['dateCreated'];
            //TODO 添加成功处理逻辑
            $ret['error'] = 0;
            $ret['dateCreated'] = substr($dateCreated, 0, 4) . '-' . substr($dateCreated, 4, 2) . '-' . substr($dateCreated, 6, 2) . ' ' . substr($dateCreated, 8, 2) . ':' . substr($dateCreated, 10, 2) . ':' . substr($dateCreated, -2);;
            $ret['smsMessageSid'] = $smsmessage['smsMessageSid'];
        }
        return $ret;
    }

}

